﻿/**
 * ...
 * @author krozalski
 */

package hapi.flash.util;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;
import hapi.log.LogLevel;

class AssetsUtil {
	
	static var bitmapDataCache:Hash<BitmapData> = new Hash();
	static var domain:ApplicationDomain = ApplicationDomain.currentDomain;
	
	public static function createBitmapData<T>( className:String ):T {
		var clazz:Class<T> = safeResolveClass(className);
		var r = Type.createInstance(clazz, [null, null]);
		if ( r == null) {
			throw "Could not create bitmpa data of class " + className + "";
		}
		return r;
	}
	
	public static function createBitmap( bitmapDataClassName:String ):Bitmap {
		var bitmapData:BitmapData;
		if (bitmapDataCache.exists(bitmapDataClassName)) {
			bitmapData = bitmapDataCache.get(bitmapDataClassName);
		}else {
			bitmapData = createBitmapData( bitmapDataClassName );
			bitmapDataCache.set(bitmapDataClassName, bitmapData);
		}
		return new Bitmap(bitmapData);
	}
	
	public static function createSprite<T>( className:String ):T {
		var clazz:Class<T> = safeResolveClass(className);
		var r = Type.createEmptyInstance(clazz);
		if ( r == null) {
			throw "Could not create sprite of class " + className + "";
		}
		return r;
	}
	
	public static function create<T>( className:String ):T {
		var clazz:Class<T> = safeResolveClass(className);
		var r = Type.createEmptyInstance(clazz);
		if ( r == null) {
			throw "Could not create asset of class " + className + "";
		}
		return r;
	} 
	
	public static function switchDomain(?appDomain:ApplicationDomain):Void {
		if(appDomain != domain ) {
			domain = appDomain;
			if (domain == null) domain = ApplicationDomain.currentDomain;
			bitmapDataCache = new Hash();
		}
	}
	
	public static function safeResolveClass<T>( className:String ) {
		var clazz:Class<T> = cast domain.getDefinition(className);
		if(clazz == null && domain != ApplicationDomain.currentDomain ) clazz = cast ApplicationDomain.currentDomain.getDefinition(className);
		if ( clazz == null ) {
			throw "Class " + className + " could not be resolved";
		}
		return clazz;
	}
	
	public static function resolveClassName(obj:Dynamic):String untyped {
		return __global__["flash.utils.getQualifiedClassName"](obj);
	}
}